﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using DevExpress.XtraBars.Ribbon;
using System.Configuration;
using DevExpress.XtraEditors.Design;
using System.Data.SqlClient;
using Instrument;
using Common;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.Utils;
using System.IO;

namespace UI
{
    public partial class QueryForm : RibbonForm
    {
        public QueryForm()
        {
            InitializeComponent();
            IEnumerable<Production> productionList = DataBaseOperation.GetInstance().GetAllProduction();
            RepositoryItemComboBox comboBox = (RepositoryItemComboBox)modelSelect.Edit;
            foreach(var item in productionList)
            {
                comboBox.Items.Add(item.Model);
            }
            comboBox.SelectedValueChanged += ComboBox_SelectedValueChanged;
        }

        private void ComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            Model = modelSelect.EditValue.ToString();
        }

        DateTime StartTime;
        DateTime StopTime;
        string Model;
        DataTable DataSource;
        bool AllowExport = false;
        string[] StatisticRow;


        private void skinRibbonGalleryBarItem1_GalleryItemClick(object sender, GalleryItemClickEventArgs e)
        {
            string caption = string.Empty;

            if (skinRibbonGalleryBarItem1.Gallery == null) return;

            caption = skinRibbonGalleryBarItem1.Gallery.GetCheckedItems()[0].Tag.ToString();//获取真实的名称，没有汉化的

            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings["SkinString"].Value = caption;
            configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("AppSettings");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string Topic = configuration.AppSettings.Settings["SkinString"].Value;
            defaultLookAndFeel1.LookAndFeel.SetSkinStyle(Topic);//设置主题样式
        }

        private void timeStartSelect_EditValueChanged(object sender, EventArgs e)
        {
            StartTime = (DateTime)timeStartSelect.EditValue;
            AllowExport = false;
        }

        private void timeStopSelect_EditValueChanged(object sender, EventArgs e)
        {
            StopTime = (DateTime)timeStopSelect.EditValue;
            AllowExport = false;
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if(StartTime == null || StopTime == null || Model == null)
            {
                MessageBox.Show("请设置查询条件");
                return;
            }
            if(StartTime > StopTime)
            {
                MessageBox.Show("时间顺序有误，请重新设置时间");
                return;
            }
            gridView1.Columns.Clear();
            string strStartTime = StartTime.ToString("yyyy-MM-dd") + " 00:00";
            string strStopTime = StopTime.ToString("yyyy-MM-dd") + " 23:59";
            Production production = DataBaseOperation.GetInstance().GetMatchProduction(Model);
                DataTable dt = new DataTable();

            DataColumn dc = dt.Columns.Add("序号", typeof(int));
            dc.AutoIncrement = true;//自动增加 
            dc.AutoIncrementSeed = 1;//起始为1 
            dc.AutoIncrementStep = 1;//步长为1 

            string ColumnsName = "";
            for (int i = 1; i <= production.ResistanceCount; i++)
            {
                ColumnsName += "电阻" + i.ToString() + ",";
            }
            string sqlString = "SELECT MeasureTime," + ColumnsName + "case when(Quality='Qualified') then '合格' when(Quality='Unqualified') then '不合格' end as Quality FROM " + Model
                + "_MeasureRecord WHERE MeasureTime BETWEEN '"+ strStartTime + "' AND '" + strStopTime + "';";
            using (SqlConnection conn = (SqlConnection)new SqlDatabaseProxy().CreateConnection())
            {
                SqlDataAdapter sda = new SqlDataAdapter(sqlString, (SqlConnection)new SqlDatabaseProxy().CreateConnection());
                sda.Fill(dt);
            }

            
            ConfigGridView(dt.Columns.Count);//配置界面gridView

            DataTable stringTable = TransDatatable(dt);
            DataRow newRow = stringTable.NewRow();
            AddStatisticsRow(dt, newRow, production);
            stringTable.Rows.Add(newRow);
            gridControl1.DataSource = stringTable;
            DataSource = stringTable;

            AllowExport = true;
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if(DataSource == null || AllowExport == false)
            {
                MessageBox.Show("请先执行查询");
            }
            else
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xls";
                saveDialog.Filter = "Excel文件|*.xls";
                if(saveDialog.ShowDialog() == DialogResult.OK)
                {
                    string path = saveDialog.FileName;
                    ExportExcel(DataSource, path);
                }
                
            }
            
        }
        private void ConfigGridView(int count)
        {
            for(int i = 0;i < count;i ++)
            {
                GridColumn gridColumn = gridView1.Columns.Add();
                gridColumn.Visible = true;
                if(i == 0)
                {
                    gridColumn.Caption = "序号";
                    gridColumn.FieldName = "序号";
                    gridColumn.OptionsColumn.AllowEdit = false;
                    gridColumn.OptionsFilter.AllowFilter = false;
                    gridColumn.OptionsColumn.AllowSort = DefaultBoolean.False;
                    gridColumn.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
                }
                else if(i == 1)
                {
                    gridColumn.Caption = "测试时间";
                    gridColumn.FieldName = "MeasureTime";
                    gridColumn.OptionsColumn.AllowEdit = false;
                    gridColumn.OptionsFilter.AllowFilter = false;
                    gridColumn.OptionsColumn.AllowSort = DefaultBoolean.False;
                    gridColumn.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
                }
                else if(i == count - 1)
                {
                    gridColumn.Caption = "质量";
                    gridColumn.FieldName = "Quality";
                    gridColumn.OptionsColumn.AllowEdit = false;
                    gridColumn.OptionsFilter.AllowFilter = false;
                    gridColumn.OptionsColumn.AllowSort = DefaultBoolean.False;
                    gridColumn.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
                }
                else
                {
                    gridColumn.Caption = "电阻" + (i - 1).ToString();
                    gridColumn.FieldName = "电阻" + (i - 1).ToString();
                    gridColumn.OptionsColumn.AllowEdit = false;
                    gridColumn.OptionsFilter.AllowFilter = false;
                    gridColumn.OptionsColumn.AllowSort = DefaultBoolean.False;
                    gridColumn.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
                }
            }
        }
        private DataTable TransDatatable(DataTable BeTransed)
        {
            DataTable target = new DataTable();
            
            foreach(DataColumn item in BeTransed.Columns)
            {
                DataColumn dataColumn = new DataColumn(item.ColumnName, typeof(string));
                target.Columns.Add(dataColumn);
            }

            for (int i = 0; i < BeTransed.Rows.Count; i++)
            {
                DataRow dataRow = target.NewRow();
                for (int j = 0; j < BeTransed.Columns.Count; j++)
                {
                    dataRow[j] = BeTransed.Rows[i][j].ToString();
                }
                target.Rows.Add(dataRow);
            }

            return target;
        }
        private void AddStatisticsRow(DataTable dt,DataRow stringRow,Production production)
        {
            int ColumnIndex = 0;
            stringRow[0] = "合格率";
            foreach (DataColumn column in dt.Columns)
            {
                if (column.ColumnName.Contains("电阻"))
                {
                    string temp = column.ColumnName;
                    int rowCount = dt.Rows.Count;
                    double quaifiedValue = production.QualifiedResistance;
                    double offset = production.AllowOffset;
                    int sumQualified = 0;
                    for (int i = 0; i < rowCount; i++)
                    {
                        if (Math.Abs((double)dt.Rows[i][temp] - quaifiedValue) < offset && (double)dt.Rows[i][temp] > -1)
                        {
                            sumQualified++;
                        }
                    }
                    string qualifiedRate = (((float)sumQualified) / ((float)rowCount)).ToString("P1");
                    stringRow[ColumnIndex] = qualifiedRate;
                }
                else if (column.ColumnName == "Quality")
                {
                    string temp = column.ColumnName;
                    int rowCount = dt.Rows.Count;
                    int sumQualified = 0;
                    for (int i = 0; i < rowCount; i++)
                    {
                        if ((string)dt.Rows[i][temp] == "合格")
                        {
                            sumQualified++;
                        }
                    }
                    string qualifiedRate = (((float)sumQualified) / ((float)rowCount)).ToString("P1");
                    stringRow[ColumnIndex] = qualifiedRate;
                }
                ColumnIndex++;
            }
        }
        public void ExportExcel(DataTable dt,string fileName)
        {
            //创建文件
            FileStream file = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write);

            //以指定的字符编码向指定的流写入字符
            StreamWriter sw = new StreamWriter(file, Encoding.GetEncoding("GB2312"));

            StringBuilder strbu = new StringBuilder();

            //写入标题
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (i == 0)
                {
                    strbu.Append("序号" + "\t");
                }
                else if (i == 1)
                {
                    strbu.Append("测试时间" + "\t");
                }
                else if (i == dt.Columns.Count - 1)
                {
                    strbu.Append("质量" + "\t");
                }
                else
                {
                    strbu.Append("电阻" + (i - 1).ToString() + "\t");
                }
            }
            //加入换行字符串
            strbu.Append(Environment.NewLine);

            //写入内容
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    strbu.Append(dt.Rows[i][j] + "\t");
                }
                strbu.Append(Environment.NewLine);
            }

            sw.Write(strbu.ToString());
            sw.Flush();
            file.Flush();

            sw.Close();
            sw.Dispose();

            file.Close();
            file.Dispose();

            MessageBox.Show("搞完");
        }
    }
}
